<template>
  <div>
    <!--电池报警-->
    <!--条件筛选-->
    <Spin :spinning="loading" tip="Loading...">
      <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="110" @filterChange="changeHandle" @onCollapse="collapseHandle" @resetChange="resetHandle"></TopFilter>

      <FilterTable
        ref="businessMangerTable"
        columnsRef="repair_repairReception_repairBusinessManager_main"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :isSelectColumn="false"
        :datakey="'records'"
        :onColumnsChange="(columns) => (this.columns = columns)"
        :onRowSelectChange="(columns) => (this.selectColumns = columns)"
      >
        <template slot="controls">
          <multiuse-button size="small" type="primary" icon="el-icon-download" :click="exportData.bind()">下载</multiuse-button>
        </template>
      </FilterTable>

      <BaseDialog :visible.sync="selectDelearFlag" :title="'服务中心选择'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <DealerFrom @close="delearClose" @save="delearSave" selectionType="multiple"></DealerFrom>
      </BaseDialog>
      <!-- 分派弹框 -->
      <BaseDialog :visible.sync="selectAssignFlag" :title="'分派'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <AssignFrom :formData="resData" @close="assignClose"></AssignFrom>
      </BaseDialog>
      <!-- 审核弹框 -->
      <BaseDialog :visible.sync="selectCheckFlag" :title="'审核'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <CheckFrom :formData="resData" @close="checkClose"></CheckFrom>
      </BaseDialog>
      <!-- 明细 -->
      <Drawer :visible.sync="actions.visible" :title="actions.title" width="90%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <showDialog :formData="resData" @close="close" />
      </Drawer>
    </Spin>
  </div>
</template>

<script>
import { getListByPage, getListForExport, selectDetail, updateState } from '@/api/serviceass/batteryAlarm/batteryAlarmManage';
import { getCitys, getDistrict } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import ownerSeacher from '../../../partsmanage/claim/approve/ownerSeacher';
import DealerFrom from './DealerFrom.vue';
import AssignFrom from './AssignFrom';
import CheckFrom from './CheckFrom';
import showDialog from './showDialog';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils';
export default {
  name: 'servicessbatteryservicebookingindex',
  mixins: [dictionary],
  components: {
    ownerSeacher,
    DealerFrom,
    AssignFrom,
    CheckFrom,
    showDialog,
  },
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      fetchParams: {},
      fetchApi: getListByPage,
      selectDelearFlag: false,
      selectAssignFlag: false,
      selectCheckFlag: false,
      dealerData: [],
      selectDealerData: [],
      resData: {},
      actions: { title: '', visible: false, data: null },
      provinceList: [],
      cityList: [],
      regionList: [],
      rowData: {},
      loading: false,
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
        },
        {
          type: 'INPUT',
          label: '报警名称',
          fieldName: 'alarmName',
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'state',
          itemList: this.createDictList('5566'),
        },
        {
          type: 'SELECT',
          label: '省份',
          fieldName: 'province',
          placeholder: '请选择...',
          itemList: this.createRegionList(),
          change: (val) => {
            this.provinceChange(val);
          },
        },
        {
          type: 'SELECT',
          label: '城市:',
          fieldName: 'city',
          placeholder: '请选择...',
          itemList: [],
          change: (val) => {
            this.cityChange(val);
          },
        },
        {
          type: 'SELECT',
          label: '区县:',
          fieldName: 'region',
          placeholder: '请选择...',
          itemList: [],
        },
        {
          type: 'INPUT',
          label: '服务中心',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => (this.selectDelearFlag = true)} />
              </div>
            );
          },
        },
        {
          type: 'RANGE_DATE',
          label: '报警时间',
          fieldName: 'alarmTimeStart|alarmTimeEnd',
          valueFormat: 'yyyy-MM-dd',
          placeholder: '请选择',
        },
        {
          type: 'RANGE_DATE',
          label: '分派时间',
          fieldName: 'assignTimeStart|assignTimeEnd',
          valueFormat: 'yyyy-MM-dd',
          placeholder: '请选择',
        },
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 190,
          render: (props, h) => {
            return (
              <div>
                <multiuse-button
                  size="mini"
                  type="text"
                  disabled={props.row.state === 55661001 || props.row.state === 55661007 || props.row.state === 55661008 ? false : true}
                  onClick={() => this.assignHandle(props.row)}
                >
                  分派
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" disabled={props.row.state === 55661003 ? false : true} onClick={() => this.checkHandle(props.row)}>
                  审核
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button size="mini" type="text" onClick={() => this.showHandle(props.row)}>
                  明细
                </multiuse-button>
                <el-divider direction="vertical" />
                <multiuse-button
                  size="mini"
                  type="text"
                  disabled={props.row.state === 55661001 || props.row.state === 55661005 || props.row.state === 55661006 || props.row.state === 55661008 ? true : false}
                  onClick={() => this.revocation(props.row)}
                >
                  撤回
                </multiuse-button>
              </div>
            );
          },
        },
        {
          title: '消息编号',
          dataIndex: 'code',
          sorter: true,
          width: 180,
        },
        {
          title: '消息种类',
          dataIndex: 'type',
          sorter: true,
          width: 100,
          dictItems: [
            { text: '国际报警', value: 1 },
            { text: '自定义报警', value: 2 },
            { text: '阈值报警', value: 3 },
            { text: '预警', value: 4 },
          ],
        },
        {
          title: '状态',
          dataIndex: 'state',
          sorter: true,
          dictItems: this.createDictList('5566'),
          width: 130,
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          sorter: true,
          width: 160,
        },
        {
          title: '报警级别',
          dataIndex: 'alarmLevel',
          sorter: true,
          dictItems: [
            { text: '一级报警', value: 1 },
            { text: '二级报警', value: 2 },
            { text: '三级报警', value: 3 },
          ],
        },
        {
          title: '报警名称',
          dataIndex: 'alarmName',
          sorter: true,
        },
        {
          title: '报警时间',
          dataIndex: 'alarmTime',
          sorter: true,
        },
        {
          title: '接收时间',
          dataIndex: 'receiveTime',
          sorter: true,
        },
        {
          title: '服务中心代码',
          dataIndex: 'dealerCode',
          sorter: true,
          width: 160,
        },
        {
          title: '服务中心简称',
          dataIndex: 'dealerShortname',
          sorter: true,
          width: 160,
        },
        {
          title: '分派时间',
          dataIndex: 'assignTime',
          sorter: true,
          width: 160,
        },
        {
          title: '处理时间',
          dataIndex: 'opAT',
          sorter: true,
          exportFormat: {
            t: 'd',
          },
          width: 160,
        },
        {
          title: '审批时间',
          dataIndex: 'checkAt',
          sorter: true,
        },
        {
          title: '经度',
          dataIndex: 'eastLongitude',
          sorter: true,
        },
        {
          title: '纬度',
          dataIndex: 'northLatitude',
          sorter: true,
          width: 160,
        },
        {
          title: '省份',
          dataIndex: 'province',
          sorter: true,
          width: 160,
        },
        {
          title: '城市',
          dataIndex: 'city',
          sorter: true,
          width: 160,
        },
        {
          title: '区县',
          dataIndex: 'region',
          sorter: true,
          width: 160,
        },
        {
          title: '具体地址',
          dataIndex: 'address',
          sorter: true,
          width: 160,
        },
        {
          title: '报警分类',
          dataIndex: 'alarmClass',
          sorter: true,
          width: 160,
          dictItems: this.createDictList('5592'),
        },
        {
          title: '分析意见',
          dataIndex: 'analyzeNode',
          sorter: true,
          width: 160,
        },
      ];
    },
    changeHandle(val) {
      val.alarmTimeEnd && (val.alarmTimeEnd = val.alarmTimeEnd.split(' ')[0] + ' 23:59:59');
      val.assignTimeEnd && (val.assignTimeEnd = val.assignTimeEnd.split(' ')[0] + ' 23:59:59');
      this.provinceList = this.topFilterList.find((item) => item.fieldName === 'province').itemList;
      this.provinceList.forEach((x) => {
        if (x.value === val.province) {
          val.province = x.text;
        }
      });
      this.cityList = this.topFilterList.find((item) => item.fieldName === 'city').itemList;
      this.cityList.forEach((x) => {
        if (x.value === val.city) {
          val.city = x.text;
        }
      });
      this.regionList = this.topFilterList.find((item) => item.fieldName === 'region').itemList;
      this.regionList.forEach((x) => {
        if (x.value === val.region) {
          val.region = x.text;
        }
      });
      this.fetchParams = Object.assign(
        {},
        this.fetchParams,
        val,
        { dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ? this.selectDealerData : null },
        { xhrAbort: false }
      );
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async exportData() {
      getListForExport(this.fetchParams).then((res) => {
        console.log('res', res);
        exportExcelFile(res.data, '电池报警信息');
      });
    },
    //关闭
    delearClose() {
      this.selectDelearFlag = false;
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    //保存
    delearSave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach((item) => {
        this.selectDealerData.push(item.dealerCompanyCode);
      });
      this.selectDelearFlag = false;
    },
    assignHandle(row) {
      this.resData = row;
      this.selectAssignFlag = true;
    },
    assignClose() {
      this.selectAssignFlag = false;
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    checkHandle(val) {
      this.resData = val;
      this.selectCheckFlag = true;
    },
    checkClose() {
      this.selectCheckFlag = false;
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    async showHandle(row) {
      let res = await selectDetail({ bwId: row.bwId });
      if (res.resultCode == 200) {
        this.resData = res.data;
        this.actions = { visible: true, title: '明细' };
      }
    },
    close() {
      this.actions = { visible: false };
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    async provinceChange(val) {
      this.topFilterList.find((x) => x.fieldName === 'city').initialValue = '';
      this.topFilterList.find((x) => x.fieldName === 'city').itemList = [];
      this.topFilterList.find((x) => x.fieldName === 'region').initialValue = '';
      this.topFilterList.find((x) => x.fieldName === 'region').itemList = [];
      // 获取市下拉框
      if (val != '') {
        const res = await getCitys(val);
        this.topFilterList.find((item) => item.fieldName === 'city').itemList = res.data.map((x) => ({ value: x.regionId + '', text: x.regionName }));
      }
    },
    async cityChange(val) {
      this.topFilterList.find((x) => x.fieldName === 'region').initialValue = '';
      this.topFilterList.find((x) => x.fieldName === 'region').itemList = [];
      if (val != '') {
        const res = await getDistrict(val);
        this.topFilterList.find((item) => item.fieldName === 'region').itemList = res.data.map((x) => ({ value: x.regionId + '', text: x.regionName }));
      }
    },
    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCompanyCode: null }, { xhrAbort: false });
    },
    async revocation(row) {
      this.$confirm('是否确认撤回', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        this.rowData.bwId = row.bwId;
        this.rowData.state = 55661008;
        this.loading = true;
        let res = await updateState(this.rowData);
        if (res.resultCode === 200) {
          this.loading = false;
          this.fetchParams = Object.assign({}, this.fetchParams);
          return this.$notify.success({ title: '提示信息', message: '撤回成功' });
        } else {
          this.loading = false;
        }
      });
    },
  },
};
</script>
